package mapper

import observable.Observable
import observable.ObservableProxy
import observer.Observer

/**
 * 转换后新的被观察者，就是将原来的被观察者装饰了下
 */
class DecorateObservable<from, to>(
    observable: ObservableProxy<from>,//转换前的被观察者
    private val observableMapper: DataMapper<from, to>//转换函数
) : AbstractDecorateObservable<from, to>(observable) {//继承至观察者装饰抽象类

    override fun subscribeProxy(observer: Observer<to>) {
        //实例化一个发送from数据的观察者
        observable.subscribe(object : Observer<from> {
            override fun onNext(obj: from) {
                // 数据转换后，通过发送to数据的观察者发送
                val change = observableMapper.change(obj)
                dispatchObserve {
                    observer.onNext(change)
                }
            }

            override fun onSubscribe() {
                dispatchObserve {
                    observer.onSubscribe()
                }
            }

            override fun onError(throwable: Throwable) {
                dispatchObserve {
                    observer.onError(throwable)
                }
            }

            override fun onComplete() {
                dispatchObserve {
                    observer.onComplete()
                }
            }
        })
    }
}